<?php
namespace app\admin\services;

use app\common\services\BaseService;
use app\common\util\Assert;
use app\common\util\DateTimeUtil;
use app\common\util\weixin\ResponseToUser;
use app\common\util\weixin\WxApi;

class WxDialogService extends BaseService
{
    public function __construct()
    {
        $viewName = '(select d.*,m.avatar,m.nickname,m.username,dm.create_time last_time,dm.content last_content
                from wx_dialog d
                inner join member m on m.openid=d.openid
                inner join wx_dialog_message dm on dm.id=d.last_message_id
            ) t';
        parent::__construct('', $viewName);
    }

    public function getDialogMessages($dialog_id)
    {
        return [true, M('wx_dialog_message')->where(['dialog_id' => $dialog_id])->select()];
    }

    public function sendToDialog($data)
    {
        Assert::notEmpty($data, ['id', 'content']);
        $dialog_id = $data['id'];
        $content = $data['content'];
        $now = DateTimeUtil::now();
        $msg_id = M('wx_dialog_message')->add([
            'dialog_id' => $dialog_id,
            'content' => trim($content),
            'create_time' => $now,
            'is_reply' => 1
        ]);
        $openid = M('wx_dialog')->where(['id' => $dialog_id])->getField('openid');
        WxApi::init();
        ResponseToUser::text($openid, json_decode(json_encode($content)));
        M('wx_dialog')->where(['id' => $dialog_id])->setField('last_message_id', $msg_id);
        return [true, ['create_time' => $now, 'msg_id' => $msg_id]];
    }

    public function getNewMessages($data)
    {
        Assert::notEmpty($data, ['id', 'msg_id']);
        $dialog_id = $data['id'];
        $msg_id = $data['msg_id'];
        return [true, M('wx_dialog_message')->where(['is_reply' => 0, 'dialog_id' => $dialog_id, 'id' => ['gt', $msg_id]])->select()];
    }

}